// 认证页面JavaScript
class AuthApp {
    constructor() {
        this.defaultUsers = {
            'admin': { password: '123456', role: 'admin', name: '管理员' },
            'student': { password: '123456', role: 'student', name: '学生' },
            'teacher': { password: '123456', role: 'teacher', name: '教师' }
        };
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadSavedCredentials();
    }

    bindEvents() {
        // 登录表单提交
        const loginForm = document.getElementById('loginForm');
        if (loginForm) {
            loginForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleLogin();
            });
        }

        // 注册表单提交
        const registerForm = document.getElementById('registerForm');
        if (registerForm) {
            registerForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleRegister();
            });
        }

        // 回车键提交
        document.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                const activeForm = document.querySelector('.auth-form:not([style*="display: none"])');
                if (activeForm) {
                    const submitBtn = activeForm.querySelector('button[type="submit"]');
                    if (submitBtn) {
                        submitBtn.click();
                    }
                }
            }
        });
    }

    async handleLogin() {
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value;
        const rememberMe = document.getElementById('rememberMe').checked;

        // 验证输入
        if (!username || !password) {
            this.showStatus('请填写用户名和密码', 'error');
            return;
        }

        try {
            // 调用后端登录API
            const response = await fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            });

            const data = await response.json();

            if (data.status === 'success') {
                // 保存用户信息到本地存储（用于记住我功能）
                if (rememberMe) {
                    const userInfo = {
                        username: username,
                        role: this.defaultUsers[username]?.role || 'user',
                        name: this.defaultUsers[username]?.name || username,
                        loginTime: new Date().toISOString()
                    };
                    localStorage.setItem('rustAgentUser', JSON.stringify(userInfo));
                }

                this.showStatus('登录成功，正在跳转...', 'success');
                
                // 延迟跳转
                setTimeout(() => {
                    window.location.href = data.redirect || '/dashboard';
                }, 1000);
            } else {
                this.showStatus(data.message || '登录失败', 'error');
            }
        } catch (error) {
            console.error('登录请求失败:', error);
            // 如果API调用失败，回退到前端验证
            if (this.validateUser(username, password)) {
                this.showStatus('登录成功，正在跳转...', 'success');
                setTimeout(() => {
                    window.location.href = '/dashboard';
                }, 1000);
            } else {
                this.showStatus('用户名或密码错误', 'error');
            }
        }
    }

    handleRegister() {
        const username = document.getElementById('regUsername').value.trim();
        const email = document.getElementById('regEmail').value.trim();
        const password = document.getElementById('regPassword').value;
        const confirmPassword = document.getElementById('regConfirmPassword').value;
        const agreeTerms = document.getElementById('agreeTerms').checked;

        // 验证输入
        if (!username || !email || !password || !confirmPassword) {
            this.showStatus('请填写所有必填字段', 'error');
            return;
        }

        if (password !== confirmPassword) {
            this.showStatus('两次输入的密码不一致', 'error');
            return;
        }

        if (password.length < 6) {
            this.showStatus('密码长度至少6位', 'error');
            return;
        }

        if (!agreeTerms) {
            this.showStatus('请同意服务条款和隐私政策', 'error');
            return;
        }

        // 检查用户名是否已存在
        if (this.defaultUsers[username]) {
            this.showStatus('用户名已存在', 'error');
            return;
        }

        // 模拟注册成功
        this.showStatus('注册成功！请使用新账户登录', 'success');
        
        // 清空表单
        document.getElementById('registerForm').reset();
        
        // 切换到登录页面
        setTimeout(() => {
            this.showLogin();
        }, 1500);
    }

    validateUser(username, password) {
        const user = this.defaultUsers[username];
        return user && user.password === password;
    }

    showStatus(message, type = 'info') {
        const statusElement = document.getElementById('statusMessage');
        if (statusElement) {
            statusElement.textContent = message;
            statusElement.className = `status-message ${type}`;
            statusElement.style.display = 'block';

            // 3秒后自动隐藏
            setTimeout(() => {
                statusElement.style.display = 'none';
            }, 3000);
        }
    }

    loadSavedCredentials() {
        const savedUser = localStorage.getItem('rustAgentUser') || sessionStorage.getItem('rustAgentUser');
        if (savedUser) {
            try {
                const userInfo = JSON.parse(savedUser);
                document.getElementById('username').value = userInfo.username;
                document.getElementById('rememberMe').checked = true;
            } catch (e) {
                console.error('解析保存的用户信息失败:', e);
            }
        }
    }
}

// 全局函数
function showRegister() {
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');
    
    if (loginForm && registerForm) {
        loginForm.style.display = 'none';
        registerForm.style.display = 'block';
        registerForm.classList.add('visible');
    }
}

function showLogin() {
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');
    
    if (loginForm && registerForm) {
        registerForm.style.display = 'none';
        loginForm.style.display = 'block';
        loginForm.classList.add('visible');
    }
}

function togglePassword() {
    const passwordInput = document.getElementById('password');
    const toggleBtn = document.querySelector('.toggle-password i');
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        toggleBtn.className = 'fas fa-eye-slash';
    } else {
        passwordInput.type = 'password';
        toggleBtn.className = 'fas fa-eye';
    }
}

function toggleRegPassword() {
    const passwordInput = document.getElementById('regPassword');
    const toggleBtn = document.querySelector('#regPassword + .toggle-password i');
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        toggleBtn.className = 'fas fa-eye-slash';
    } else {
        passwordInput.type = 'password';
        toggleBtn.className = 'fas fa-eye';
    }
}

function toggleRegConfirmPassword() {
    const passwordInput = document.getElementById('regConfirmPassword');
    const toggleBtn = document.querySelector('#regConfirmPassword + .toggle-password i');
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        toggleBtn.className = 'fas fa-eye-slash';
    } else {
        passwordInput.type = 'password';
        toggleBtn.className = 'fas fa-eye';
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.authApp = new AuthApp();
}); 